//
// Created by zyl on 2021/5/5.
//
#include "string.h"
#include "stdio.h"
#include "str_test.h"
void test_strlen(void) {
    char *str = "我是你爸爸";
    size_t i = strlen(str);
    //显示的字节长度
    printf("str的字符创长度是:%d", i);//utf-8 15
}

void test_strcpy(void) {
    char s1[32] = "hello world";
    char s2[32] = "hello s2";
    printf("s1:%s\ns2:%s", s1, s2);
    //正常情况
    strcpy(s1, s2);
    printf("\ns1: %s", s1);
    //将数据复制在一个内存较小的区域
    char s3[3] = "1";
    printf("\ns3[3] = %s", s3);
    //可以显示完整的s1, 但是内存不安全,可能对其他内存进行了覆盖
    strcpy(s3, s1);
    printf("\ns3[3] = %s", s3);
}

void test_strncpy(void) {
    char s1[32] = "hello the world";
    char s2[3] = "1";
    strncpy(s2, s1, 2);
    printf("%s", s2);
}
/**
 * 字符串拼接
 */
void test_strcat(void) {
    char pre[32] = "hello the pre";
    char back[32] = "hello the back";
    char *string = strcat(pre, back);
    if (pre == string) {
        printf("%s", pre);
    }
}
/**
 * 字符串比较函数
 * 大于 1
 * 等于 0
 * 小于 -1
 */
void test_strcmp(void) {
    char str1[] = "我是你爸爸";
    char str2[] = "我是你爸爸";
    char str3[] = "1";
    char str4[] = "2";
    int i = strcmp(str1, str2);
    printf("str4 ,str3 = %d\n", strcmp(str4, str3));
    if (i == 0) {
        printf("str1 = str2");
    }
    
}

void test_strchr(void) {
    char str1[] = "我是你爸爸";

    char target[] = "你";
    char *string = findUnicode(str1, target, strlen(target), strlen(str1));
    printf("\n%c%c%c", string[0], string[1], string[2]);
}

void test_strstr(void) {
    char *str1 = "我是你爸爸";
    char *needle = "你";
    char *string = strstr(str1, needle);
    printf("%s", string);
}
char *findUnicode(char *target, char *charTarget, unsigned int charTargetLength,unsigned int targetLength) {
    char *value = NULL;
    if (charTargetLength <= 0) {
        return NULL;
    }
    char *string1 = strchr(target, charTarget[0]);
    if (string1 == NULL) {
        return NULL;
    }
    value = string1;
    unsigned long i1 = string1 - target;
    if (i1 + charTargetLength > targetLength) {
        return NULL;
    }
    unsigned int i2 = charTargetLength - 1;
    for (int j = 0; j < i2; ++j) {
        if (target[i1 + j + 1] != charTarget[j + 1]) {
            return NULL;
        }
    }
    return value;
    
}